package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Follow;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import util.KeyGen;
import util.ParameterCheck;
import dao.FollowDao;
import dao.ItemDao;

/**
 * Servlet implementation class Follow
 */
public class FollowAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(Follow.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");

		String userid = "";
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			if ("user".equals(cookies[i].getName())) {
				userid = cookies[i].getValue();
			}
		}

		String iid = request.getParameter("itemid");

		log.debug("userid:" + userid + ";itemid:" + iid);

		String msg = "";
		String result = "";

		if (ParameterCheck.isEmpty(userid, iid)) {
			msg = "parameter is illegal";
		} else {

			userid = KeyGen.getId(userid);
			int uid = Integer.parseInt(userid);
			int itemid = KeyGen.convertCode2Id(iid);

			Follow fo = new Follow();
			fo.setUid(uid);
			fo.setItemid(itemid);
			int re = new FollowDao().insert(fo);
			if (re > 0) {
				msg = "ok";
			} else {
				msg = "sorry , we got an error here ,please try again later";
			}
			result = String.valueOf(re);

			log.info(new ItemDao().updateHot(itemid, 3));

		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", msg);
		jsonObject.put("res", result);
		out.print(jsonObject.toString());

	}

}
